import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/UI/HiNote/HiNote.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../Util/HttpGo.dart';
import '../../Widget/MyDialog.dart';

class Calendar extends StatefulWidget {
  Function() onAddClass;

  Calendar({Key? key, required this.onAddClass}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return CalendarState();
  }
}

class CalendarState extends State<Calendar> {
  DateTime _focusedDay = DateTime.now();
  DateTime _selectedDay = DateTime.now();

  List<dynamic> dateTimes = [];

  getDateMonth() {
    dateTimes.clear();
    setState(() {});
    HttpGo(context).post("/Lesson/GetCalendarDate", {
      "studentId": Global.studentId,
      "year": _focusedDay.year,
      "month": _focusedDay.month,
      "timeZone": DateTime.now().timeZoneOffset.inMinutes,
    }, (data) {
      dateTimes = data["dateTimes"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  List<dynamic> lessons = [];

  getClassDay() {
    //mark 這裡有個bug，點擊日曆控件選擇selectDay後，selectDay會變成UTC0格式，所以取年月日重新創建一個date
    DateTime begin = DateTime(_selectedDay.year, _selectedDay.month, _selectedDay.day);
    DateTime end = begin.add(Duration(days: 1));
    String beginDay = getUtcTime(begin);
    String endDay = getUtcTime(end);
    lessons.clear();
    HttpGo(context).post("/Lesson/GetBookedLessonList", {
      "studentId": Global.studentId,
      "beginDateTime": beginDay,
      "endDateTime": endDay,
      "limit": 1000,
    }, (data) {
      for (var item in data["lessonList"] ?? []) {
        if (item["lessonState"] == 1 || item["lessonState"] == 2) {
          lessons.add(item);
        }
      }
      setState(() {});
    }, (code, error) => showToast(error), showLoading: true);
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getDateMonth();
      getClassDay();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Container(
          decoration: Global.getWhiteBg_shadow(8, MyColor.EE),
          margin: EdgeInsets.fromLTRB(20, 0, 20, 0),
          child:
              // CalendarDatePicker(
              //     initialDate: DateTime.now(),
              //     firstDate: DateTime(2021, 1, 1),
              //     lastDate: DateTime(2099, 12, 31),
              //     onDateChanged: (DateTime dt) {
              //       print("${dt.year}-${dt.month}-${dt.day}");
              //     })
              TableCalendar(
                  firstDay: DateTime(2022, 1, 1),
                  lastDay: DateTime(2050, 12, 31),
                  focusedDay: _focusedDay,
                  headerStyle: HeaderStyle(titleCentered: true, formatButtonVisible: false),
                  calendarStyle: CalendarStyle(outsideDaysVisible: false),
                  selectedDayPredicate: (day) {
                    return isSameDay(_selectedDay, day);
                  },
                  onDaySelected: (selectedDay, focusedDay) {
                    print("onDaySelected:$selectedDay");
                    setState(() {
                      _selectedDay = selectedDay;
                      _focusedDay = focusedDay; // update `_focusedDay` here as well
                    });
                    getClassDay();
                  },
                  onPageChanged: (focusedDay) {
                    print("onPageChanged:$focusedDay");
                    _focusedDay = focusedDay;
                    getDateMonth();
                  },
                  eventLoader: (day) {
                    for (String dt in dateTimes) {
                      if (getTimeByUtc(dt)?.day == day.day) {
                        return [" 1"];
                      }
                    }
                    return [];
                  },
                  calendarBuilders: CalendarBuilders(singleMarkerBuilder: (BuildContext context, DateTime day, dynamic event) {
                    return Container(height: 6, width: 6, decoration: Global.getBg(Colors.green, 3));
                  }))),
      Padding(
        padding: EdgeInsets.all(20),
        child:
            Text(getStrTime(_selectedDay, DateUtil.YMD), style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: MyColor.C58)),
      ),
      ListView.builder(
          itemCount: lessons.length,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (BuildContext context, int index) {
            return ItemClass(lessons[index], onRefresh: () {
              getClassDay();
              getDateMonth();
            });
          }),
      GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: widget.onAddClass,
          child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
            LocalImage("add.png", width: 12, padding: EdgeInsets.fromLTRB(0, 12, 4, 12)),
            Text("我要訂課", style: TextStyle(fontSize: 14, color: MyColor.C66))
          ])),
      Container(height: 16),
    ]));
  }
}

class ItemClass extends StatelessWidget {
  dynamic data;
  Function() onRefresh;

  ItemClass(this.data, {required this.onRefresh});

  static const int Success = 1;
  static const int WaitingAccept = 2;

  // lessonState: (課堂狀態)
  // 　0 = Cancel , (課程取消)
  // 　1 = Success , (訂課成功)
  // 　2 = WaitingAccept , (等待老師同意)
  // 　3 = Reject (訂課失敗)

  @override
  Widget build(BuildContext context) {
    toHiNote() {
      PageUtil().open(context, HiNote());
    }

    getClassUrl() {
      HttpGo(context).get("/Lesson/GetClassroomUrl?classroomId=${data["classroomId"]}", {}, (data) {
        PageUtil().launchURL("${data["classroomUrl"]}"); //進入教室
      }, (code, message) => showToast(message));
    }

    cancelClass() {
      var param = {"studentId": Global.studentId, "classroomId": data["classroomId"]};
      HttpGo(context).post("/Lesson/GetCancelBookingMessage", param, (data) {
        showBtn2Dialog(context, data, "取消", () {}, "確定", () {
          HttpGo(context).post("/Lesson/CancelBooking", param, (data) {
            onRefresh();
            showToast("取消課程成功");
          }, (code, error) => showToast(error));
        });
      }, (code, error) => showToast(error));
    }

    DateTime? startTime = getTimeByUtc(data["beginTime"]);
    DateTime? endTime = getTimeByUtc(data["endTime"]);
    String time = getStrTime(startTime, DateUtil.HM) + " - " + getStrTime(endTime, DateUtil.HM);
    return Container(
        decoration: Global.getWhiteBg_shadow(8, MyColor.EE),
        margin: EdgeInsets.fromLTRB(20, 0, 20, 8),
        padding: EdgeInsets.all(16),
        child: Column(children: [
          Row(children: [
            LocalImage("clock.png", width: 18, height: 18),
            Container(width: 8),
            Text("$time", style: TextStyle(fontSize: 16, color: MyColor.Pink, fontWeight: FontWeight.bold))
          ]),
          Row(children: [
            Container(
              margin: EdgeInsets.symmetric(vertical: 4),
              constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width - 140),
              child: Text("${data["lessonName"]}", style: TextStyle(fontSize: 14, color: MyColor.C58, fontWeight: FontWeight.bold)),
            ),
            Container(width: 8, height: 40),
            Button("${data["plateformShortName"]}", height: 28, width: 28, bgColor: MyColor.C7D, radius: 20, fontSize: 14)
          ]),
          Row(children: [
            Text("${data["teacherName"]}(${data["teacherId"]})", style: TextStyle(fontSize: 12, color: MyColor.C58)),
            Container(width: 8),
            LocalImage("chat-alt3-active.png", width: 20, onTap: () {
              //todo
              // PinChat.startChat(toUserId: "${data["teacherId"]}");
            })
          ]),
          Container(height: 16),
          data["lessonState"] == Success
              ? Row(children: [
                  ItemClassBtn("預習/複習", onTap: toHiNote),
                  ItemClassBtn("進入教室", onTap: getClassUrl),
                  ItemClassBtn("取消課程", fontColor: MyColor.Pink, onTap: cancelClass),
                ])
              : ItemClassBtn("待老師同意"),
        ]));
  }
}

class ItemClassBtn extends StatelessWidget {
  String text;
  Color? fontColor;
  Function()? onTap;

  ItemClassBtn(this.text, {this.fontColor, this.onTap});

  @override
  Widget build(BuildContext context) {
    return Expanded(
        child: Button(text,
            bgColor: MyColor.F3,
            radius: 4,
            fontSize: 12,
            fontColor: fontColor ?? Color(0xff5a87ba),
            height: 32,
            onTap: onTap,
            margin: EdgeInsets.fromLTRB(8, 0, 8, 0)));
  }
}
